package com.cupk.rotaryguard.monitor.utils;

import com.cupk.common.base.config.Contant;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import com.opencsv.exceptions.CsvValidationException;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * CSV工具类
 *
 * @author tjy
 */
public class CsvUtil {
    /**
     * 将结果数据输出为二维字符串数组方便查看
     *
     * @param filePath
     * @param hasHeader
     * @return
     */
    public static String[][] readCSV(String filePath, boolean hasHeader) {
        List<String[]> dataList = new ArrayList<>();
        try (CSVReader reader = new CSVReader(new FileReader(filePath))) {
            String[] header = null;
            if (hasHeader) {
                header = reader.readNext();
            }
            String[] nextLine;
            while ((nextLine = reader.readNext()) != null) {
                String[] values = new String[nextLine.length];
                for (int i = 0; i < nextLine.length; i++) {
                    values[i] = nextLine[i];
                }
                dataList.add(values);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String[][] dataArray = new String[dataList.size()][];
        for (int i = 0; i < dataArray.length; i++) {
            dataArray[i] = dataList.get(i);
        }
        return dataArray;
    }

    /**
     * 将设备数据写入csv文件供模型调用
     *
     * @param dataList
     * @param csvFilePath
     */
    public static void writeCsvFile(List<String[]> dataList, String csvFilePath) {
        try (CSVWriter writer = new CSVWriter(new FileWriter(csvFilePath), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END)) {
            String[] header = {"DE_time", "FE_time", "RPM"};
            writer.writeNext(header);
            writer.writeAll(dataList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        List<String[]> list = new ArrayList<>();
        String[] strings1 = {"1","2","9999"};
        String[] strings2 = {"1","2","9999"};
        String[] strings3 = {"1","2","9999"};
        list.add(strings1);
        list.add(strings2);
        list.add(strings3);
        writeCsvFile(list,"/Users/tjy/GraduationDesign/Microservices-based-Rotating-Equipment-Status-Monitoring-and-Fault-Diagnosis-Platform/rotaryGuard/rotaryGuard-monitor/src/main/resources/dataset/test/TEST1.csv");
    }

    /**
     * 删除指定文件内容
     *
     * @param file
     */
    public static void deleteFileContent(File file) {
        try {
            FileWriter fw = new FileWriter(file, false);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("");
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
